//
//  UserServer.m
//  WeCommunity
//
//  Created by mac on 2017/6/20.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "UserServer.h"

#define USERVISIT_CLASS_NAME @"UserVisits"

static UserServer * userServer = nil;

@implementation UserServer

+(UserServer *)shared
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        userServer = [[UserServer alloc] init];
        
    });
    return userServer;
}

-(ContactModel *)getSelfContact
{
    //必须登陆后
    AVUser *currentUser = [AVUser currentUser];
    if (!currentUser) {
        return [ContactModel new];
    }
    return [ContactModel setValueFormObject:currentUser];
}

#pragma mark - 保存昵称
-(void)saveUserNickName:(NSString *)nickName complete:(void(^)(BOOL success,NSString * error,NSString * nickName))complete
{
    [[AVUser currentUser] setObject:nickName forKey:@"nickName"];
    [[AVUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            NSString * name = [[AVUser currentUser] objectForKey:@"nickName"];
            complete(YES,nil,name);
        }else{
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }
    }];
}

#pragma mark - 保存微信号
-(void)saveUserWXUserName:(NSString *)userName  complete:(void(^)(BOOL success,NSString * error,NSString * WXUserName))complete
{
    [[AVUser currentUser] setObject:userName forKey:@"WXUserName"];
    [[AVUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            NSString * name = [[AVUser currentUser] objectForKey:@"WXUserName"];
            complete(YES,nil,name);
        }else{
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }
    }];
}

#pragma mark - 保存头像
-(void)saveHeadImage:(UIImage*)image complete:(void(^)(BOOL success,NSString * error,NSString * imageUrl))complete
{
//    NSData *data = UIImagePNGRepresentation(image);
    NSData *data = UIImageJPEGRepresentation(image, 0.5);
    AVFile *file = [AVFile fileWithData:data];
    [[AVUser currentUser] setObject:file forKey:@"headImage"];
    [[AVUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            AVFile * file = [[AVUser currentUser] objectForKey:@"headImage"];
            complete(YES,nil,file.url);
        }else{
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }
    }];
}

#pragma mark - 保存性别
-(void)saveUserSex:(NSString*)sex complete:(void(^)(BOOL success,NSString * error,NSString * sex))complete
{
    [[AVUser currentUser] setObject:sex forKey:@"sex"];
    [[AVUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            NSString * sexStr = [[AVUser currentUser] objectForKey:@"sex"];
            complete(YES,nil,sexStr);
        }else{
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }
    }];
}

#pragma mark - 增减积分
-(void)addCoins:(NSNumber *)number complete:(void(^)(BOOL success,NSString * error,NSNumber* coins))complete
{
 
    [[AVUser currentUser]fetchInBackgroundWithKeys:@[@"coins",@"usedCoins"] block:^(AVObject * _Nullable object, NSError * _Nullable error) {
        if(error){
            complete(NO,error.userInfo[@"NSLocalizedDescription"],[[AVUser currentUser] objectForKey:@"coins"]);
        }
        
        NSNumber *coins = [object objectForKey:@"coins"];
        NSInteger iCoins = [number integerValue]+[coins integerValue];
        [[AVUser currentUser]setObject:[NSNumber numberWithInteger:iCoins] forKey:@"coins"];
        
        if([number integerValue] < 0){//使用金币
            NSNumber *usedCoins = [object objectForKey:@"usedCoins"];
            NSInteger iUsedCoins = - [number integerValue]+[usedCoins integerValue];
            [[AVUser currentUser]setObject:[NSNumber numberWithInteger:iUsedCoins] forKey:@"usedCoins"];
        }
        
        [[AVUser currentUser]saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
            if(error){
                complete(NO,error.userInfo[@"NSLocalizedDescription"],[[AVUser currentUser] objectForKey:@"coins"]);
            }else{
                complete(YES,nil,[[AVUser currentUser] objectForKey:@"coins"]);
            }
            
        }];
        
    }];
 
}

#pragma mark - LeanCloud - 注册
-(void)registerUser:(ContactModel *)contact
           complete:(void(^)(BOOL succees,NSString *error,ContactModel * contact))completeBlock
{
    AVUser *user = [AVUser user];
    user.username = contact.userName;
    user.password = contact.password;
    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            ContactModel * userContact = [ContactModel new];
            userContact.userName = user.username;
            userContact.password = user.password;
            
            completeBlock(YES,nil,userContact);
        }else{
            completeBlock(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }
    }];
}

#pragma mark - 退出登录
-(void)logOut
{
    [AVUser logOut];
}

#pragma mark - 登录
-(void)LoginWithUser:(ContactModel *)contact
           complete:(void(^)(BOOL succees,NSString *error,ContactModel * contact))completeBlock
{
    [AVUser logInWithUsernameInBackground:contact.userName password:contact.password block:^(AVUser *user, NSError *error) {
        if (error) {
            completeBlock(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        } else {
            //更新 session
            [user refreshSessionTokenWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
                
            }];

            //检查用户信息
            NSString * nickName = [user objectForKey:@"nickName"];
            if (!nickName || nickName.length == 0) {
                [[UserServer shared] creatNewUserComplete:^(BOOL success,NSString *error) {
                    if (success) {
                        ContactModel * userContact = [ContactModel new];
                        userContact.userName = user.username;
                        userContact.password = user.password;
                        userContact.sessionToken = user.sessionToken;
                        userContact.objectId = user.objectId;
                        completeBlock(YES,nil,userContact);
                    }else{
                        completeBlock(NO,error,nil);
                    }
                }];
            }else{
                ContactModel * userContact = [ContactModel new];
                userContact.userName = user.username;
                userContact.password = user.password;
                userContact.sessionToken = user.sessionToken;
                userContact.objectId = user.objectId;
                completeBlock(YES,nil,userContact);
            }
            //更新
            
        }
    }];
}

#pragma mark - 创建一个新的默认用户信息
-(void)creatNewUserComplete:(void(^)(BOOL success ,NSString *error))complete
{
    [[AVUser currentUser] setObject:[self getRandomNickName:10] forKey:@"nickName"];
    [[AVUser currentUser] setObject:@"" forKey:@"WXUserName"];
    [[AVUser currentUser] setObject:@"0" forKey:@"sex"];
    
//    NSData *data = UIImagePNGRepresentation([UIImage imageNamed:@"defaultHead"]);
    NSData *data = UIImageJPEGRepresentation([UIImage imageNamed:@"defaultHead"], 0.5);
    AVFile *file = [AVFile fileWithData:data];
    [[AVUser currentUser] setObject:file forKey:@"headImage"];
    
    [[AVUser currentUser] saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            complete(YES,nil);
        }else{
            complete(NO,error.userInfo[@"NSLocalizedDescription"]);
        }
    }];
}

#pragma mark -  每一个新用户默认设置一个昵称
-(NSString *)getRandomNickName:(NSInteger)length
{
    NSString *letters = @"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    NSMutableString *randomString = [NSMutableString stringWithCapacity:length];
    
    for (NSInteger i = 0; i < length; i++) {
        [randomString appendFormat: @"%c", [letters characterAtIndex: arc4random_uniform((int)[letters length])]];
    }
    return randomString;
}

#pragma mark -  验证session
-(void)verifySessionTokenComplete:(void(^)(BOOL available))complete
{
    AVUser * currentUser = [AVUser currentUser];
    [currentUser isAuthenticatedWithSessionToken:currentUser.sessionToken callback:^(BOOL succeeded, NSError * _Nullable error) {
        complete(succeeded);
    }];
}

#pragma mark - 查询某个用户的拜访记录
-(void)findContactVisitsWithObjectId:(NSString *)contactId
                          complete:(void(^)(BOOL success,NSString *error, ContactVisitRecordModel * resultModel))complete
{
    AVQuery *query = [AVQuery queryWithClassName:USERVISIT_CLASS_NAME];
    [query whereKey:@"contactId" equalTo:contactId];
    query.limit = 1;
    [query findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            complete(NO,error.userInfo[@"NSLocalizedDescription"],nil);
        }else{
            if (objects.count > 0) {
                ContactVisitRecordModel * model =  [ContactVisitRecordModel setValueFormObject:objects.firstObject];
                complete(YES,nil,model);
            }else{
                complete(YES,@"没有此人的拜访记录",nil);
            }
        }
    }];
}

#pragma mark - 拜访某个用户
-(void)mySelfVisitSomePerson:(NSString *)contactId
                    complete:(void(^)(BOOL success ,NSString *error))complete
{
    //查询最新的数据
    [self findContactVisitsWithObjectId:contactId complete:^(BOOL success, NSString *error,ContactVisitRecordModel * resultModel) {
        if (success) {
            if (!resultModel) {
                //新建一个拜访
                [self creatVisitRecordForContact:contactId visitIds:@[[UserInfoManger shared].contact.objectId] complete:^(BOOL success, NSString *error) {
                    complete(success,error);
                }];
            }else{
                //添加一个拜访
                [self addVisitRecordForContactObjectId:resultModel.objectId visitId:[UserInfoManger shared].contact.objectId complete:^(BOOL success, NSString *error) {
                    complete(success,error);
                }];
            }
        }else{
            complete(NO,error);
        }
    }];
}

#pragma mark - 新创建一个用户拜访记录
-(void)creatVisitRecordForContact:(NSString *)contactId
                         visitIds:(NSArray *)visitIds
                         complete:(void(^)(BOOL success ,NSString *error))complete
{
    AVObject * dynamic = [AVObject objectWithClassName:USERVISIT_CLASS_NAME];
    [dynamic setObject:contactId forKey:@"contactId"];
    [dynamic setObject:visitIds forKey:@"visitList"];
    
    [dynamic saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (succeeded) {
                complete(YES,nil);
            }else{
                complete(NO,error.userInfo[@"NSLocalizedDescription"]);
            }
        });
    }];
}

#pragma mark - 添加一个用户拜访记录
-(void)addVisitRecordForContactObjectId:(NSString *)objectId
                                visitId:(NSString *)visitId
                               complete:(void(^)(BOOL success ,NSString *error))complete
{
    AVObject * dynamic =[AVObject objectWithClassName:USERVISIT_CLASS_NAME objectId:objectId];
    //添加拜访人
    [dynamic addObject:visitId forKey:@"visitList"];
    [dynamic saveInBackgroundWithBlock:^(BOOL succeeded, NSError * _Nullable error) {
        if (succeeded) {
            complete(YES,nil);
        }else{
            complete(NO,error.userInfo[@"NSLocalizedDescription"]);
        }
    }];
}




@end
